package edu.ped.android.bluetooth;

import java.io.IOException;

import edu.ped.android.nfc.TicTacToeServerActivity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;

/*Thread connection client bluetooth*/
public class ConnectThread extends Thread {
	private final BluetoothSocket mmSocket;
	private BluetoothAdapter mBluetoothAdapter;
	private Handler handler;
	
	public ConnectThread(BluetoothDevice device,Handler handler) {
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		this.handler=handler;
		BluetoothSocket tmp = null;
		try {
			tmp = device.createRfcommSocketToServiceRecord(TicTacToeServerActivity.uuid);
		} catch (IOException e) { }
		mmSocket = tmp;
	}

	public void run() {
		mBluetoothAdapter.cancelDiscovery();
		try {
			mmSocket.connect();
		} catch (IOException connectException) {
			try {
				mmSocket.close();
			} catch (IOException closeException) { }
			return;
		}
		handler.sendEmptyMessage(TicTacToeServerActivity.SET_CLIENT_SOCKET);
		return;
	}

	public void cancel() {
		try {
			mmSocket.close();
		} catch (IOException e) { }
	}
	
	public BluetoothSocket getSocket(){
		return mmSocket;
	}
}
